package com.springboot.cloud.sysadmin.organization.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.cloud.common.core.utils.StringUtils;
import com.springboot.cloud.sysadmin.organization.dao.UserDeptMapper;
import com.springboot.cloud.sysadmin.organization.entity.po.UserDept;
import com.springboot.cloud.sysadmin.organization.service.IUserDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by ZengJian on 2021/2/3 0003 上午 9:22
 */
@Service
@Slf4j
public class UserDeptService extends ServiceImpl<UserDeptMapper, UserDept> implements IUserDeptService {

    @Override
    public boolean saveBatch(String userId, Set<String> depts) {
        if (ArrayUtil.isNotEmpty(queryByUserId(userId))) {
            removeByUserId(userId);
        }
        if (ArrayUtil.isEmpty(depts))
            return true;
        removeByUserId(userId);
        Set<UserDept> userGroups = depts.stream().map(deptId -> new UserDept(userId, deptId)).collect(Collectors.toSet());
        return saveBatch(userGroups);
    }

    @Override
    public boolean removeByUserId(String userId) {
        QueryWrapper<UserDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserDept::getUserId, userId);
        return remove(queryWrapper);
    }

    @Override
    public Set<String> queryByUserId(String userId) {
        QueryWrapper<UserDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<UserDept> userGroupList = list(queryWrapper);
        return userGroupList.stream().map(UserDept::getDeptId).collect(Collectors.toSet());
    }
}

